package com.haiqiu.common.utils.files;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.InvalidFileNameException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author HaiQiu
 * @date 2021/1/21 21:21
 * @desc 阿里云oss存储配置文件
 **/
@Component
public class OssUtil {

    private static final String PLACEHOLDER = "/";
    /**
     * 访问OSS的域名
     */
    @Value("${oss.endpoint}")
    private String endpoint;


    /**
     * accessKeyId和accessKeySecret是OSS的访问密钥
     */
    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    /**
     * accessKeyId和accessKeySecret是OSS的访问密钥
     */
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;


    /**
     * Bucket用来管理所存储Object的存储空间
     */
    @Value("${oss.bucketName}")
    private String bucketName;

    /**
     * oss自定义绑定域名
     */
    @Value("${oss.host}")
    private String host;


    public String upload(MultipartFile file, String folder) {
        if (file == null) {
            try {
                throw new FileNotFoundException("未发现上传文件");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isBlank(folder)) {
            try {
                throw new FileNotFoundException("无效所属文件夹");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        assert file != null;
        String originalName = file.getOriginalFilename();
        String fileType = null;
        if (StringUtils.isNotBlank(originalName)) {
            fileType = originalName.substring(originalName.lastIndexOf('.'));
        }
        if (StringUtils.isBlank(fileType)) {
            throw new InvalidFileNameException(originalName, "未知的文件类型!");
        }
        String filePath =  folder + PLACEHOLDER + originalName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName,filePath, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return getUrl(filePath);
    }

    /**
     * 拼接url地址
     *
     * @param filePath 文件地址
     * @return 文件oss访问地址
     */
    private String getUrl(String filePath) {
        /**
         * oss访问地址
         */
        String ossFileHost = host + filePath;
        return ossFileHost;
    }

}
